
import axios from "axios"

const service = axios.create({
    baseURL: "https://toutiao.itheima.net/v1_0",
    timeout: 10000
})

service.interceptors.request.use(config => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    if (userInfo.token) {
        config.headers.Authorization = `Bearer ${userInfo.token}`

    }

    return config
})

service.interceptors.response.use(

    response => (response.data ? response.data.data : response.data),

    error => {

        if (error.response.status === 401) {
            //token is invalid
            const info = JSON.parse(localStorage.getItem('userInfo'))

            const refreshToken = info?.refresh_token

            if (refreshToken) {
                //如果有就换取新的token
                // console.log('❄️ - refreshToken:', refreshToken)

                axios({
                    method: 'PUT',
                    url: 'https://toutiao.itheima.net/v1_0/authorizations',
                    headers: {
                        Authorization: 'Bearer ' + refreshToken
                    }
                }).then(res => {
                    const token = res.data.data.token
                    localStorage.setItem('userInfo', JSON.stringify({ ...info, token }))
                    return service(error.config)
                }).catch(err => {
                    console.log(err)
                    console.log('❄️ - err:', err.response.data.message)
                    if (err.response.data.message === "refresh_token失效") {
                        localStorage.removeItem("userInfo")
                        location.href = "/login"
                        return Promise.reject(new Error("请重新登录"))

                    }
                })

            } else {
                localStorage.removeItem("userInfo")
                location.href = "/login"
                return Promise.reject(new Error("请重新登录"))

            }



        }
    }





)

export default service
